﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using PivotalTrackerAPI;

namespace PivotalTFSSync
{
	public partial class frmMain : Form
	{
		public frmMain()
		{
			InitializeComponent();
		}

		private void btnGetStories_Click(object sender, EventArgs e)
		{
			GetPivotalStories();
		}

		private void GetPivotalStories()
		{
			Cursor = Cursors.WaitCursor;
			IPivotal p = new Pivotal(txtPivotalUsername.Text, txtPivotalPassword.Text);
			try
			{
				IEnumerable<Iteration> iterations = p.GetIteration((Project)cboPivotalProjects.SelectedItem,
																   ((Pivotal.IterationVersion)cboPivotalIteration.SelectedItem));
				PopulateTreeview(iterations.First().Stories.stories);
			}
			catch (Exception ex)
			{
				LogError(ex);
			}
			Cursor = Cursors.Arrow;
		}

		private void LogError(Exception exception)
		{
			lstMessages.Items.Add(exception.Message);
		}

		private void PopulateTreeview(IEnumerable<Story> stories)
		{
			tvwDetails.Nodes.Clear();

			foreach (Story story in stories)
			{
				string key = story.Id.ToString();
				TreeNode node = tvwDetails.Nodes.Add(key, story.Name, story.Type);
				node.Tag = story;

				if (story.Description.Trim().Length > 0)
				{
					node.Nodes.Add(string.Concat(key, "-2"), story.Description.Trim(), "empty");
				}
			}
		}

		private void frmMain_Load(object sender, EventArgs e)
		{
			LoadPivotalIterations();
		}

		private void LoadPivotalProjects()
		{
			IPivotal p = new Pivotal(txtPivotalUsername.Text, txtPivotalPassword.Text);
			cboPivotalProjects.DataSource = p.GetAllProjects();
			cboPivotalProjects.DisplayMember = "Name";
		}

		private void LoadTFSProjects()
		{
			try
			{
				var tfs = new TFS(txtTFSServerURL.Text);
				cboProjects.DataSource = tfs.GetProjects();
				cboProjects.DisplayMember = "Name";
			}
			catch (Exception exception)
			{
				LogError(exception);
			}
		}

		private void LoadPivotalIterations()
		{
			cboPivotalIteration.Items.Add(Pivotal.IterationVersion.All);
			cboPivotalIteration.Items.Add(Pivotal.IterationVersion.Backlog);
			cboPivotalIteration.Items.Add(Pivotal.IterationVersion.Current);
			cboPivotalIteration.Items.Add(Pivotal.IterationVersion.Done);
		}

		private void LoadTFSIterations(string projectname)
		{
			try
			{
				var tfs = new TFS(txtTFSServerURL.Text);
				cboDestinationIteration.DataSource = tfs.GetIterationPaths(projectname);
				cboDestinationIteration.DisplayMember = "Name";
			}
			catch (Exception exception)
			{
				LogError(exception);
			}
		}

		private void btnSyncSelected_Click(object sender, EventArgs e)
		{
			SyncCheckedItems();
		}

		private void SyncCheckedItems()
		{
			Cursor = Cursors.WaitCursor;
			int currentPriority = int.Parse(txtStartPriority.Text);
			int priorityStep = int.Parse(txtPriorityStep.Text);
			var tfs = new TFS(txtTFSServerURL.Text);
			string projectname = ((Microsoft.TeamFoundation.WorkItemTracking.Client.Project)cboProjects.SelectedItem).Name;
			string iterationpath = string.Concat(projectname, "\\",
												 ((Node)cboDestinationIteration.SelectedItem).Name, "\\",
												 ((Node)cboSubPath.SelectedItem).Name);

			foreach (TreeNode node in tvwDetails.Nodes)
			{
				if (node.Checked)
				{
					var story = (Story)node.Tag;
					story.Priority = currentPriority;
					tfs.AddPivotalStoryToTFS(story, projectname, iterationpath);
					currentPriority = currentPriority + priorityStep;
				}
			}
			Cursor = Cursors.Arrow;
		}

		private void cboProjects_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (cboProjects.SelectedItem != null)
			{
				LoadTFSIterations(((Microsoft.TeamFoundation.WorkItemTracking.Client.Project)cboProjects.SelectedItem).Name);
			}
		}

		private void cboPivotalProjects_Enter(object sender, EventArgs e)
		{
			if (cboPivotalProjects.Items.Count == 0)
			{
				Cursor = Cursors.WaitCursor;
				LoadPivotalProjects();
				Cursor = Cursors.Arrow;
			}
		}

		private void cboProjects_Enter(object sender, EventArgs e)
		{
			if (cboProjects.Items.Count == 0)
			{
				LoadTFSProjects();
			}
		}


		private static bool IsChildNode(TreeNode node)
		{
			return node.Parent != null;
		}

		private void tvwDetails_BeforeCheck(object sender, TreeViewCancelEventArgs e)
		{
			if (IsChildNode(e.Node))
			{
				e.Node.Parent.Checked = !e.Node.Parent.Checked;
				e.Cancel = true;
			}
		}

		private void cboDestinationIteration_SelectedIndexChanged(object sender, EventArgs e)
		{
			cboSubPath.DataSource = ((Microsoft.TeamFoundation.WorkItemTracking.Client.Node)cboDestinationIteration.SelectedItem).ChildNodes;
			cboSubPath.DisplayMember = "Name";
		}
	}
}